package com.zy.impl;

import com.zy.constant.AuthConstants;
import com.zy.factory.LoginStrategyFactory;
import com.zy.strategy.LoginStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义的认证流程
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取请求对象 RequestContextHolder:请求内容的上下文对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //从请求头中获取登录类型
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        //判断请求来自那个系统
//        if (loginType.equals(AuthConstants.SYS_USER_LOGIN)) {
//            //商城后台管理系统用户
//
//        } else if (loginType.equals(AuthConstants.MEMBER_LOGIN)){
//            //商城用户购买系统用户
//        }
        if (!StringUtils.hasText(loginType)) {
            //loginType为空，无登录类型
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        //通过登录策略工厂获取具体的登录策略对象
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        //执行具体登录逻辑
        return instance.realLogin(username);
    }
}

